package org.misalen.web.server.controllers.user;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.misalen.annotations.ControllerApi;
import org.misalen.annotations.InterfaceApi;
import org.misalen.utils.TextUtil;
import org.misalen.web.database.model.mysql.pro.ProUser;
import org.misalen.web.database.model.mysql.pro.ProVideoReward;
import org.misalen.web.database.model.mysql.pro.ProWebAdvertising;
import org.misalen.web.database.model.mysql.pro.ProWebAdvertisingPreview;
import org.misalen.web.database.model.mysql.pro.ProWebPayInfo;
import org.misalen.web.database.model.mysql.pro.ProWebReward;
import org.misalen.web.database.util.PaginationFrom;
import org.misalen.web.server.config.ErrorCode;
import org.misalen.web.server.config.ServerResult;
import org.misalen.web.server.config.ServerUrl;
import org.misalen.web.server.config.Uncertain;
import org.misalen.web.server.controllers.BaseController;
import org.misalen.web.server.exception.CustomerException;
import org.misalen.web.server.forms.user.WebAdvertisingAddForm;
import org.misalen.web.server.forms.user.WebAdvertisingAreaListForm;
import org.misalen.web.server.forms.user.WebAdvertisingDetailForm;
import org.misalen.web.server.forms.user.WebAdvertisingMylistForm;
import org.misalen.web.server.forms.user.WebAdvertisingPrepaidForm;
import org.misalen.web.server.forms.user.WebAdvertisingPreviewForm;
import org.misalen.web.server.forms.user.WebAdvertisingRedwarsForm;
import org.misalen.web.server.forms.user.WebAdvertisingShareForm;
import org.misalen.web.server.forms.user.WebAdvertisingVicinityListForm;
import org.misalen.web.server.result.Empty;
import org.misalen.web.server.util.FormUtil;
import org.misalen.web.service.pay.alipay.AliPayParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ControllerApi(value = "网页广告", description = "", index = 800)
@RequestMapping(value = ServerUrl.UserWebAdvertisingControllerUrl)
public class UserWebAdvertisingController extends BaseController {

	@RequestMapping(value = "/add", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "发布广告", resultClass = { Empty.class })
	public @ResponseBody ServerResult add(@RequestBody WebAdvertisingAddForm form) throws CustomerException {
		FormUtil.validate(form);
		ProWebAdvertising advertising = new ProWebAdvertising();
		advertising.setAddTime(new Date());
		advertising.setUserId(form.getUserId());
		advertising.setAdverImagesUrl(form.getAdverImagesUrl());
		advertising.setAdverSlogan(form.getAdverSlogan());
		advertising.setMobileOrLink(form.getMobileOrLink());
		advertising.setPromotionExpenses(form.getPromotionExpenses());
		advertising.setPromotionNumber(form.getPromotionNumber());
		advertising.setPromotionMode(form.getPromotionMode());
		advertising.setPromotionCity(form.getPromotionCity());
		advertising.setPromotionDistance(form.getPromotionDistance());
		advertising.setLongitude(form.getLongitude());
		advertising.setLatitude(form.getLatitude());
		advertising.setCarrierUrl(form.getCarrierUrl());
		advertising.setCarrierId(form.getCarrierId());
		advertising.setState("noPay");
		advertising.setGrabThe(TextUtil.stateToString(false));
		proWebAdvertisingRepository.save(advertising);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("webId", advertising.getPrimaryKey());
		return ServerResult.ok(map);
	}

	@RequestMapping(value = "/preview", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "生成预览连接", resultClass = { ProWebAdvertisingPreview.class })
	public @ResponseBody ServerResult preview(HttpServletRequest request, @RequestBody WebAdvertisingPreviewForm form)
			throws CustomerException {
		FormUtil.validate(form);
		ProWebAdvertisingPreview advertising = new ProWebAdvertisingPreview();
		advertising.setAddTime(new Date());
		advertising.setUserId(form.getUserId());
		advertising.setAdverImagesUrl(form.getAdverImagesUrl());
		advertising.setAdverSlogan(form.getAdverSlogan());
		advertising.setMobileOrLink(form.getMobileOrLink());
		advertising.setCarrierUrl(form.getCarrierUrl());
		proWebAdvertisingPreviewRepository.save(advertising);
		advertising.setPreviewUrl(getBaseHost(request) + Uncertain.adminUrl + "/pro-web-advertising-preview/"
				+ advertising.getPrimaryKey());
		return ServerResult.ok(advertising);
	}

	@RequestMapping(value = "/prepaid", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "预支付", resultClass = { Empty.class })
	public @ResponseBody ServerResult prepaid(HttpServletRequest request, @RequestBody WebAdvertisingPrepaidForm form)
			throws Exception {
		FormUtil.validate(form);
		String baseUrl = getBaseUrl(request);
		ProWebAdvertising advertising = proWebAdvertisingRepository.get(ProWebAdvertising.class, form.getWebId());
		if (advertising.getState().equals("noPay")) {
			ProWebPayInfo proWebPayInfo = new ProWebPayInfo();
			proWebPayInfo.setWebId(form.getWebId());
			proWebPayInfo.setAddTime(new Date());
			proWebPayInfo.setPayType(form.getPayType());
			proWebPayInfoRepository.save(proWebPayInfo);
			if (form.getPayType().equals("alipay")) {
				AliPayParam myParam = new AliPayParam();
				myParam.setBody(Uncertain.advertisingBody);
				myParam.setSubject(Uncertain.advertisingSubject);
				myParam.setOutTradeNo(proWebPayInfo.getWebId());
				myParam.setTotalAmount(TextUtil.changeF2Y(advertising.getPromotionExpenses().toString()));
				String param = aliPay.getAlipayInfo(myParam, Uncertain.webAliPayNotifyUrl);
				return ServerResult.ok(param);
			} else {
				String myParam = wechatPay.orderedParam(baseUrl + Uncertain.advertisingBody,
						proWebPayInfo.getWebId(), advertising.getPromotionExpenses().toString(),
						proWebPayInfo.getWebId(), getIpAddress(request), baseUrl + Uncertain.webWechatNotifyUrl);
				Map<String, Object> map = wechatPay.unifiedorder(myParam);
				return ServerResult.ok(wechatPay.clientParam(map));
			}
		} else {
			return ServerResult.error(ErrorCode.SYS_ERROR_CODE_00001);
		}
	}

	@RequestMapping(value = "/vicinity/list", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "附近任务", resultClass = { PaginationFrom.class, ProWebAdvertising.class }, include = {
			"primaryKey", "adverSlogan", "adverImagesUrl", "promotionExpenses", "grabThe", "isGet", "getMoney",
			"detailsUrl" })
	public PaginationFrom<ProWebAdvertising> vicinitylist(HttpServletRequest request,
			@RequestBody WebAdvertisingVicinityListForm form) throws CustomerException {
		FormUtil.validate(form);
		PaginationFrom<ProWebAdvertising> pagination = formToPage(form, ProWebAdvertising.class);
		pagination = proWebAdvertisingRepository.findByVicinity(form.getUserId(), form.getLatitude(),
				form.getLongitude(), pagination);
		for (ProWebAdvertising webAdvertising : pagination.getList()) {
			webAdvertising.setDetailsUrl(getBaseHost(request) + Uncertain.adminUrl
					+ "/pro-web-advertising-preview/details/" + webAdvertising.getPrimaryKey());
		}
		return pagination;
	}

	@RequestMapping(value = "/area/list", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "区域任务", resultClass = { PaginationFrom.class, ProWebAdvertising.class }, include = {
			"primaryKey", "adverSlogan", "adverImagesUrl", "promotionExpenses", "grabThe", "isGet", "getMoney",
			"detailsUrl" })
	public PaginationFrom<ProWebAdvertising> arealist(HttpServletRequest request,
			@RequestBody WebAdvertisingAreaListForm form) throws CustomerException {
		FormUtil.validate(form);
		PaginationFrom<ProWebAdvertising> pagination = formToPage(form, ProWebAdvertising.class);
		ProUser proUser = proUserRepository.get(ProUser.class, form.getUserId());
		pagination = proWebAdvertisingRepository.findByAreaa(form.getUserId(), proUser.getBelongCity(), pagination);
		for (ProWebAdvertising webAdvertising : pagination.getList()) {
			webAdvertising.setDetailsUrl(getBaseHost(request) + Uncertain.adminUrl
					+ "/pro-web-advertising-preview/details/" + webAdvertising.getPrimaryKey());
		}
		return pagination;
	}

	@RequestMapping(value = "/redwars", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "抢任务", include = { "money" }, resultClass = ProVideoReward.class)
	public @ResponseBody ServerResult redwars(@RequestBody WebAdvertisingRedwarsForm form) throws CustomerException {
		ProWebAdvertising videoInfo = proWebAdvertisingRepository.getValid(form.getWebId());
		if (videoInfo == null) {
			return ServerResult.error(ErrorCode.SYS_ERROR_CODE_10012);
		}
		long validCount = proWebRewardRepository.getValidCountByWeb(form.getWebId());
		if (validCount == 0) {
			proWebAdvertisingRepository.updateGrabThe(TextUtil.booleanToString(false), form.getWebId());
			return ServerResult.error(ErrorCode.SYS_ERROR_CODE_10012);
		}

		ProWebReward proWebReward = proWebRewardRepository.getByVideoUser(form.getUserId(), form.getWebId());
		if (proWebReward != null) {
			return ServerResult.error(ErrorCode.SYS_ERROR_CODE_10013);
		}
		proWebReward = proWebRewardRepository.getValidByVideo(form.getWebId());
		proUserRepository.updateFreezeBalance(proWebReward.getMoney(), form.getUserId());
		proWebReward.setGetTime(new Date());
		proWebReward.setUserId(form.getUserId());
		proWebRewardRepository.update(proWebReward);
		if (validCount == 1) {
			proWebAdvertisingRepository.updateGrabThe(TextUtil.booleanToString(false), form.getWebId());
		}
		return ServerResult.ok();
	}

	@RequestMapping(value = "/mylist", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "我的网页广告", resultClass = { PaginationFrom.class, ProWebAdvertising.class })
	public PaginationFrom<ProWebAdvertising> mylist(HttpServletRequest request,
			@RequestBody WebAdvertisingMylistForm form) throws CustomerException {
		FormUtil.validate(form);
		PaginationFrom<ProWebAdvertising> pagination = formToPage(form, ProWebAdvertising.class);
		pagination = proWebAdvertisingRepository.findByUser(form.getUserId(), form.getState(), pagination);
		for (ProWebAdvertising webAdvertising : pagination.getList()) {
			webAdvertising.setDetailsUrl(getBaseHost(request) + Uncertain.adminUrl
					+ "/pro-web-advertising-preview/details/" + webAdvertising.getPrimaryKey());
		}
		return pagination;
	}

	@RequestMapping(value = "/share", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "分享参数(返回url)", resultClass = { PaginationFrom.class, ProWebAdvertising.class })
	public @ResponseBody ServerResult share(HttpServletRequest request, @RequestBody WebAdvertisingShareForm form)
			throws CustomerException {
		FormUtil.validate(form);
		ProWebAdvertising webAdvertising = proWebAdvertisingRepository.get(ProWebAdvertising.class, form.getWebId());
		Map<String, String> map = new HashMap<String, String>();
		ProWebReward proWebReward = proWebRewardRepository.getByVideoUser(form.getUserId(), form.getWebId());
		if (proWebReward == null || TextUtil.stringToBoolean(proWebReward.getTimeLimit())) {
			map.put("url", getBaseHost(request) + Uncertain.adminUrl + "/pro-web-advertising-preview/details/"
					+ webAdvertising.getPrimaryKey());
		} else {
			map.put("url", getBaseHost(request) + Uncertain.adminUrl + "/pro-web-advertising-preview/share/"
					+ proWebReward.getPrimaryKey());
		}
		return ServerResult.ok(map);
	}
	
	@RequestMapping(value = "/mydetails", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "详情", resultClass = { PaginationFrom.class, ProWebReward.class })
	public PaginationFrom<ProWebReward> mydetails(@RequestBody WebAdvertisingDetailForm form) throws CustomerException {
		FormUtil.validate(form);
		PaginationFrom<ProWebReward> pagination = formToPage(form, ProWebReward.class);
		return proWebRewardRepository.getMyDetailList(form.getWebId(), pagination);
	}
	
}
